/**
 * @param {number[][]} mat
 * @return {number[][]}
 */

var updateMatrix = function (mat) {
    let res = new Array(mat.length);
    let queue = [];
    for (let i = 0; i < res.length; i++) {
        res[i] = new Array(mat[0].length).fill(Infinity);
        for (let j = 0; j < mat[i].length; j++) {
            if (mat[i][j] === 0) {
                queue.push([i, j]);
                res[i][j] = 0;
            }
        }
    }
    while (queue.length > 0) {
        let q = queue.shift();
        // 下上左右
        const dx = [1, 0, -1, 0], dy = [0, 1, 0, -1];
        const x = q[0], y = q[1], val = res[x][y] + 1;
        for (let i = 0; i < 4; i++) {
            // 下上左右
            const nx = dx[i] + x, ny = y + dy[i];
            if (nx >= mat.length || nx < 0 || ny > mat[0].length || ny < 0) continue;
            if (val < res[nx][ny]) {
                res[nx][ny] = val;
                queue.push([nx, ny]);
            }
        }
    }
    return res;
};